# 准备合并逻辑。。两个数据库字段统一
from datetime import datetime
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine

from django.conf import settings
if settings.DATABASE_TYPE == 'mysql':
    from tanxi.models.mysql.mysql_user_model import UserModel, UserManager 
    from tanxi.models.mysql.mysql_travel_model import TravelBlogModel
        
elif settings.DATABASE_TYPE == 'sqlite':
    from tanxi.models.sqlite.sqlite_user_model import SqliteUserModel as UserModel
    from tanxi.models.sqlite.sqlite_user_model import SqliteUserManager as UserManager
    # from tanxi.models.sqlite.sqlite_travel_model import SqlitetravelModel as travelModel
else:
    raise ValueError("Unsupported database type specified in settings.")

from tanxi.client.Handler.Logger import log_info
from django.utils import timezone
from django.core.exceptions import ObjectDoesNotExist


from demoPython.settings import db_config
from django.db.models import F

# 创建数据库引擎
engine = create_engine(f'mysql+mysqlconnector://{db_config["user"]}:{db_config["password"]}@{db_config["host"]}/{db_config["database"]}')
Session = sessionmaker(bind=engine)


class TravelBlogQueryHandler():
    def __init__(self):
        self.session = Session()

    def query_travel_blogs(self, id=None, city=None, title=None, author_id=None, is_published=None):
        """
        查询旅游博客，根据城市、标题、作者和发布状态进行过滤
        """
        blogs = TravelBlogModel.objects.annotate(
            author_name=F('author__name')
        ).values(
            'id', 'city', 'title', 'address', 'description', 
            'image', 'map_url', 'author_name', 'created_at',
            'updated_at', 'view_count', 'tags', 'is_published'
        )
        
        if id:
            id = int(id)
            log_info(f"旅游博客ID {id}")
            blogs = blogs.filter(id=id)
            
        if city:
            blogs = blogs.filter(city__icontains=city)
            
        if title:
            blogs = blogs.filter(title__icontains=title)
            
        if author_id:
            blogs = blogs.filter(author__name__icontains=author_id)
            
        if is_published is not None:
            blogs = blogs.filter(is_published=is_published)
            
        return blogs


class TravelBlogUpdateHandler:
    def update_or_create_travel_blog(self, blog_data):
        """
        更新或创建旅游博客
        """
        if not blog_data:
            raise ValueError("旅游博客数据不能为空")

        blog_id = blog_data.get('id')

        if blog_id:
            try:
                blog = TravelBlogModel.objects.get(id=blog_id)
                log_info(f"更新现有旅游博客: ID={blog_id}, 数据={blog_data}")

                for field, value in blog_data.items():
                    if hasattr(blog, field) and field != 'id':
                        setattr(blog, field, value)
                blog.updated_at = timezone.now()
                blog.save()
                return {'blog_id': blog.id, 'message': '旅游博客更新成功'}

            except ObjectDoesNotExist:
                raise ValueError(f"旅游博客 ID {blog_id} 不存在")
            except Exception as e:
                log_info(f"更新旅游博客失败: {e}")
                raise ValueError(f"更新旅游博客失败: {str(e)}")

        # 创建新博客
        log_info(f"创建新旅游博客: 数据={blog_data}")

        if 'author_id' not in blog_data:
            raise ValueError("创建新旅游博客时必须提供 author_id")

        defaults = {
            'city': '',
            'title': '',
            'address': '',
            'description': '',
            'image': '',
            'map_url': '',
            'is_published': False,
            'view_count': 0,
            'tags': [],
            'created_at': timezone.now(),
            'updated_at': timezone.now()
        }
        defaults.update(blog_data)
        defaults.pop('id', None)

        try:
            blog = TravelBlogModel.objects.create(**defaults)
            return {'blog_id': blog.id, 'message': '旅游博客创建成功'}
        except Exception as e:
            log_info(f"创建旅游博客失败: {e}")
            raise ValueError(f"创建旅游博客失败: {str(e)}")

    def delete_travel_blog(self, id):
        """
        删除旅游博客
        """
        TravelBlogModel.objects.filter(id=id).delete()
        return True